package connection

import (
	"broker/interface/iserver"
	"broker/utils/logger"
	"errors"
	"sync"
)

/*	连接管理模块*/

type ConnManager struct {
	connections map[uint32]iserver.IConnection //管理的连接集合
	connLock    sync.RWMutex                   //保护连接集合的读写锁
}
var connManager = &ConnManager{}
var connManagerOnce sync.Once
func NewConnManager() *ConnManager {
	connManagerOnce.Do(func() {
		connManager = &ConnManager{
			connections: make(map[uint32]iserver.IConnection),
		}
	})
	return connManager
}

// AddConnection 添加链接
func (cm *ConnManager) AddConnection(connection iserver.IConnection) {
	//保护共享资源，加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()

	cm.connections[connection.GetConnID()] = connection
	logger.Info.Println("[ConnManage] connection connID = ", connection.GetConnID(), " add to ConnManager successfully")
}

// RemoveConnection 删除链接
func (cm *ConnManager) RemoveConnection(connection iserver.IConnection) {
	//保护共享资源，加写锁
	cm.connLock.Lock()
	defer cm.connLock.Unlock()
	delete(cm.connections, connection.GetConnID())
	logger.Info.Println("[ConnManage] connection connID = ", connection.GetConnID(), " remove successfully")
}
// GetConnection 根据connID获取连接
func (cm *ConnManager) GetConnection(connID uint32) (iserver.IConnection, error) {
	//保护共享资源，加读锁
	cm.connLock.RLock()
	defer cm.connLock.RUnlock()

	if conn, ok := cm.connections[connID]; ok {
		return conn, nil
	}
	return nil, errors.New("connection not found")
}

// GetLen 得到连接总数
func (cm *ConnManager) GetLen() uint32 {
	return uint32(len(cm.connections))
}

// ClearAll 清除并断开所有连接
func (cm *ConnManager) ClearAll() {
	cm.connLock.Lock()
	defer cm.connLock.Unlock()

	//删除conn并停止conn的工作
	for connID, conn := range cm.connections {
		//停止
		conn.Stop()
		//删除
		delete(cm.connections, connID)
	}
	logger.Info.Println("[ConnManager] clear all connection successfully")
}
